package base

import (
	"gitee.com/slion/helper"
	"github.com/kataras/iris"
	"github.com/kataras/iris/middleware/logger"
	irisrecover "github.com/kataras/iris/middleware/recover"
	"github.com/sirupsen/logrus"
	"gitee.com/slion/infra"
	"time"
)

var irisApplication *iris.Application

func IrisApplication() *iris.Application{
	return irisApplication
}

type IrisServerStarter struct {
	infra.BaseStarter
}

func (i *IrisServerStarter) Init(ctx infra.StartContext){

	// 创建实例
	// 配置中间件
	initIris()

	// 日志组件配置和扩展
	irisLogger := irisApplication.Logger()
	irisLogger.Install(logrus.StandardLogger())
}

func (i *IrisServerStarter) Start(ctx infra.StartContext){

	// 把路由信息打印到控制台
	routes := irisApplication.GetRoutes()
	for _, r := range routes {
		logrus.Info(r.Trace())
	}

	// 启动iris
	port := ctx.GetProps().GetDefault("app.server.port", "8080")
	err := irisApplication.Run(iris.Addr(":" + port))
	if err != nil{
		logrus.Error(err.Error())
	}
}

// 阻塞式
func (i *IrisServerStarter) StartBlocking() bool{
	return true
}

func initIris() {
	app := iris.New()

	// recover中间件
	app.Use(irisrecover.New())
	// 日志中间件
	cfg := logger.Config{
		Status:             true,
		IP:                 true,
		Method:             true,
		Path:               true,
		Query:              true,
		// 格式化日志输出
		LogFunc: func(now time.Time, latency time.Duration, status, ip, method, path string, message interface{}, headerMessage interface{}) {
			app.Logger().Infof("%s|%s|%s|%s|%s|%s||%s|%s|",
				now.Format(helper.TimestampMillFormat), // 请求时间
				latency.String(), // 响应时间
				status,
				ip,
				method,
				path,
				headerMessage,
				message,
			)
		},
	}
	app.Use(logger.New(cfg))
	irisApplication = app
}
